package com.ff.kvm.mall.helper.impl;

import com.ff.kvm.common.eunm.StatusEnum;
import com.ff.kvm.common.third_util.WXPublicUtil;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.dao.mapper.PreRegisterMapper;
import com.ff.kvm.dao.model.PreRegister;
import com.ff.kvm.mall.helper.SpreadHelper;
import com.ff.kvm.mall.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class SpreadHelpImpl implements SpreadHelper {

    @Autowired
    private PreRegisterMapper preRegisterMapper;

    @Autowired
    private RedisService redisService;


    @Override
    public Response<Boolean> spread(String pollCode, String openId) {
        Response<Boolean> response = new Response<>();

        String unionId = WXPublicUtil.getUnionId(getAccessToken(),openId);
        PreRegister register = preRegisterMapper.findByUnionId(unionId);
        if(register != null){
            response.setData(true);
            response.setCode(StatusEnum.SUCCESS.code());
            response.setMsg(StatusEnum.SUCCESS.description());
            return response;
        }
        register = new PreRegister();
        register.setUnionId(unionId);
        register.setStatus(0);
        register.setPollCode(pollCode);
        register.setOpenId(openId);
        register.setCreateTime(new Date());
        preRegisterMapper.insert(register);
        response.setData(true);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }

    @Override
    public String getAccessToken(){
        String accessToken = redisService.getCache(Constants.WX_PUBLIC_ACCESS_TOKEN);
        if(!MyUtil.isBlank(accessToken) && !MyUtil.isBlank(accessToken.split("-----")[1])){
            Date lastTime = MyUtil.getDateH(new Date(),-2);
            Date dateTime = MyUtil.parseDate(accessToken.split("-----")[0]);
            if(!MyUtil.before(dateTime,lastTime)){
                return accessToken.split("-----")[1];
            }
        }

        accessToken = WXPublicUtil.getPublicAccessToken();
        if(!MyUtil.isBlank(accessToken)){
            redisService.putCache(Constants.WX_PUBLIC_ACCESS_TOKEN,MyUtil.formatDateYMDhms(new Date())+"-----"+accessToken);
        }
        return accessToken;
    }
}
